/* eslint-disable prettier/prettier */
import RNFS from 'react-native-fs';
import UnzipFile from '../services/UnzipFile';
import { Alert } from 'react-native';
import {WXstate} from '../enums/constant';
 /**
 * 从指定的 URL 下载文件并保存到目标文件夹
 * @param {string} url - 文件的 URL 地址
 * @param {string} filename - 保存的文件名
 * @returns {Promise<void>}
 */


 const downloadFile = async (url: string, filename: string, onProgress: (progress: number) => void): Promise<void> => {
   const targetFolder = RNFS.DocumentDirectoryPath;
   const filePath = `${targetFolder}/${filename}`;
 
   try {
     // 确保目标文件夹存在
     if (!(await RNFS.exists(targetFolder))) {
       await RNFS.mkdir(targetFolder);
     }
     if ((await RNFS.exists(filePath))) {
       console.log("已经下载过了");
       if (filename.endsWith('.zip')){
         await UnzipFile(filePath, `${targetFolder}/` + `${WXstate.PATH_NAME}` + `/${filename.slice(0,-4)}`);
       }
       return;
     }
 
     // 下载文件并显示进度
     const result = await RNFS.downloadFile({
       fromUrl: url,
       toFile: filePath,
       progressInterval: 0.01, // 每0.01更新一次进度
       progress: (res) => {
         onProgress(res.bytesWritten / res.contentLength); // 调用传入的进度回调函数
       },
     }).promise;
 
     console.log('下载结果:', result);
 
     if (result.statusCode === 200) {
       console.log(`文件已成功下载到: ${filePath}`);
     } else {
       throw new Error(`下载失败，状态码: ${result.statusCode}`);
     }
 
     if (!(await RNFS.exists(`${targetFolder}/` + `${WXstate.PATH_NAME}`))) {
       await RNFS.mkdir(`${targetFolder}/` + `${WXstate.PATH_NAME}`);
     }
 
     if (filename.endsWith('.zip')){
       await UnzipFile(filePath, `${targetFolder}/` + `${WXstate.PATH_NAME}` + `/${filename.slice(0,-4)}`);
     }
   } catch (error) {
     Alert.alert('下载失败！',
       '请重试',
       [
         {text: '确定', onPress: () => console.log('用户点击了确定')},
         {text: '取消', onPress: () => console.log('用户点击了取消'), style: 'cancel'},
       ],
       { cancelable: false });
     console.error('文件下载失败:', error.message, error.stack);
     throw error; // 重新抛出错误以供调用者处理
   }
 };
 
 export default downloadFile;